package elephant.servers.consoleserver.termos;


import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import elephant.Container;
import elephant.servers.consoleserver.AnsiColor;
import elephant.servers.consoleserver.command.SshdCommand;

/**
 * Use a thread factory
 * Support using UncaughtException.(one session one ReplThread)
 *
 * @author <a href="mailto:trygvis@java.no">Trygve Laugst&oslash;l</a>
 * @version $Id$
 */
public class ReplThread implements Closeable {
	//
	private static final Logger logger=LoggerFactory.getLogger(ReplThread.class);
	//
    private final InputStream stdin;
    private final OutputStream stdout;
    private final OutputStream stderr;
    private final Thread thread;
    //
    public ReplThread(final InputStream stdin, final OutputStream stdout, final OutputStream stderr,
                      final ReadLineEnvironment environment,final Map<String, SshdCommand> commands,
                      final Runnable onExit) {
        this.stdin = stdin;
        this.stdout = stdout;
        this.stderr = stderr;
        //
        thread = new Thread(new Runnable() {
            public void run() {
                try {
                	environment.prompt=
                	AnsiColor.getGreenContent("ElephantConsole")+
    				AnsiColor.getCyanContent("@"+environment.user)+
    				AnsiColor.getPurpleContent("#"+Container.get().getServerName())+">";
                    Repl.repl(stdin, stdout, stderr, environment,commands,environment.prompt);
                } catch (IOException e) {
                	logger.error(e.getMessage(),e);
                }
                finally {
                    try {
                        onExit.run();
                    } catch (Exception e) {
                       logger.error(e.getMessage(),e);
                    }
                }
            }
        });
        thread.setDaemon(true);
    }

    public void start() {
        thread.start();
    }

    public void close() throws IOException {
    	ReadlineUtil.closeSilently(stdin);
    	ReadlineUtil.closeSilently(stdout);
    	ReadlineUtil.closeSilently(stderr);
    }
}
